package net.documentshare;

import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.artofsolving.jodconverter.office.OfficeConnectionProtocol;

import com.sun.star.comp.helper.BootstrapException;

import net.documentshare.utils.doc.FileUtils;
import net.documentshare.utils.doc.OfficeConverter;
import net.documentshare.utils.doc.PDFConverter;
import net.simpleframework.util.HTTPUtils;
import net.simpleframework.web.AbstractWebApplication;
import net.simpleframework.web.page.PageRequestResponse;

public class DShareWebApplication extends AbstractWebApplication {
	private static final Log LOGGER = LogFactory.getLog(DShareWebApplication.class);

	@Override
	public void init(ServletConfig config) throws ServletException {
		Locale.setDefault(Locale.CHINA);
		initDoc(config);
		super.init(config);
	}

	@Override
	public boolean isSystemUrl(final PageRequestResponse requestResponse) {
		final String requestURI = HTTPUtils.getRequestURI(requestResponse.request);
		if (requestURI.indexOf("/regist.html") > -1 || requestURI.indexOf("/openid.html") > -1) {
			return true;
		}
		return super.isSystemUrl(requestResponse);
	}

	public void initDoc(ServletConfig config) {
		Properties properties = new Properties();
		try {
			InputStream in = config.getServletContext().getResourceAsStream("/config/docviewer.properties");
			properties.load(in);
		} catch (Exception e2) {
			e2.printStackTrace();
		}
		String baseConfigSpace = "docviewer.";
		String baseConverterConfigSpace = baseConfigSpace + "converter.";
		String basePdfConfigSpace = baseConverterConfigSpace + "pdf.";
		String baseOfficeConfigSpace = baseConverterConfigSpace + "office.";

		LOGGER.debug("初始化office转换服务配置....");
		try {
			OfficeConverter.setOfficeHome(new String(properties.getProperty(baseOfficeConfigSpace + "home", OfficeConverter.getOfficeHome())
					.getBytes("ISO-8859-1"), "UTF-8"));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		// OfficeConverter.setHost(new
		// String(properties.getProperty(baseOfficeConfigSpace + "host",
		// OfficeConverter.getHost()).getBytes("ISO-8859-1"), "UTF-8"));
		OfficeConverter.setPort(Integer.parseInt(properties.getProperty(baseOfficeConfigSpace + "port", OfficeConverter.getPort() + "")));
		String protocol = properties.getProperty(baseOfficeConfigSpace + "protocol");
		if (StringUtils.isNotBlank(protocol)) {
			protocol = protocol.toLowerCase();
			if (protocol.equals("socket")) {
				OfficeConverter.setConnectionProtocol(OfficeConnectionProtocol.SOCKET);
			} else if (protocol.equals("pipe")) {
				OfficeConverter.setConnectionProtocol(OfficeConnectionProtocol.PIPE);
			}
		}
		String profile = properties.getProperty(baseOfficeConfigSpace + "profile");
		if (StringUtils.isNotBlank(profile)) {
			OfficeConverter.setTemplateProfileDir(new File(profile));
		}
		LOGGER.debug("初始化服务配置完毕!启动服务....");

		try {
			OfficeConverter.startService();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		LOGGER.debug("初始PDF转换器化配置....");

		try {
			PDFConverter.setCommand(new String(properties.getProperty(basePdfConfigSpace + "command", PDFConverter.getCommand()).getBytes(
					"ISO-8859-1"), "UTF-8"));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		String max = properties.getProperty(basePdfConfigSpace + "mode.singlePage.maxThread", PDFConverter.getSinglePageModeMaxThread() + "");
		try {
			PDFConverter.setSinglePageModeMaxThread(Integer.parseInt(max));
		} catch (Exception e) {
			e.printStackTrace();
		}

		LOGGER.info("初始化PDF转换器配置完毕!");
		LOGGER.info("初始化文档阅读器主程序配置....");
		LOGGER.info("初始化文档阅读器主程序配置完毕!");
	}

	@Override
	public void destroy() {
		try {
			OfficeConverter.stopService();
		} catch (BootstrapException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.destroy();
	}

	private static final long serialVersionUID = 2617847076944785953L;
}
